import io.prometheus.metrics.core.metrics.Counter;
import io.prometheus.metrics.exporter.servlet.jakarta.PrometheusMetricsServlet;
import io.prometheus.metrics.instrumentation.jvm.JvmMetrics;
import io.prometheus.metrics.model.registry.PrometheusRegistry;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@SpringBootApplication
@ComponentScan(basePackages = "com.example.myproject")
@RestController
public class MyApplication {
    public static void main(String[] args) {
        Map<String, Object> config = new HashMap<>();
        config.put("management.endpoints.web.exposure.include", "health,info,prometheus");
        config.put("management.endpoint.prometheus.enabled", true);

        // SpringApplication.run(MyApplication.class, args);
        SpringApplication app = new SpringApplication(MyApplication.class);
        app.setDefaultProperties(config);
        app.run(args);

        JvmMetrics.builder().register();

        Counter counter = Counter.builder()
            .name("events_total")
            .help("Total number of events")
            .labelNames("status")
            .build();
            // .register();
            // .register(myRegistry);

        // PrometheusRegistry.defaultRegistry.register(counter);
        // PrometheusRegistry.defaultRegistry.unregister(counter);
        PrometheusRegistry myRegistry = new PrometheusRegistry();
        myRegistry.register(counter);

        counter.labelValues("ok").inc();
        counter.labelValues("ok").inc();
        counter.labelValues("error").inc();
   }

    // @Bean
    // public WebServerFactoryCustomizer<ConfigurableServletWebServerFactory> webServerFactoryCustomizer() {
        // return factory -> factory.setPort(8081);
    // }

    @Bean
    public ServletRegistrationBean<PrometheusMetricsServlet> createPrometheusMetricsEndpoint() {
        return new ServletRegistrationBean<>(new PrometheusMetricsServlet(), "/metrics/*");
    }

    @GetMapping("/")
    String home() {
        return "Home";
    }
}
